<!-- 编辑弹窗 -->
<template>
  <ele-modal
    form
    destroy-on-close
    :width="740"
    v-model="visible"
    :title="actionConfigs[action].title"
    @open="handleOpen"
    @close="handleCancel"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="currentRules"
      label-width="100px"
      :validate-on-rule-change="false"
      @submit.prevent=""
    >
      <el-row :gutter="16">
        <el-col :sm="12" :xs="24">
          <el-form-item label="上级地区" prop="parent_code">
            <region-select ref="regionSelectRef" v-model="form.parent_code" />
          </el-form-item>
          <el-form-item label="地区名称" prop="name">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.name"
              placeholder="请输入地区名称"
            />
          </el-form-item>

          <el-form-item label="排序号" prop="sort_number">
            <el-input-number
              :min="0"
              :max="99999"
              v-model="form.sort_number"
              placeholder="请输入排序号"
              controls-position="right"
              class="ele-fluid"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider style="margin: 8px 0 22px 0; opacity: 0.6" />
    </el-form>
    <template #footer>
      <el-button @click="resetForm">重置</el-button>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ actionConfigs[action].button }}
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import { ref, computed } from "vue";
import RegionSelect from "./region-select.vue";
import { addRegion, updateRegion, getRegion } from "@/api/base/region";
import { useFormEdit } from "@/hooks/useFormEdit";
/** 地区下拉选择组件 */
const regionSelectRef = ref(null);
const props = defineProps({
  /** 修改回显的数据 */
  data: Object,
  action: {
    type: String,
    default: "edit",
    validator: (value) => ["add", "edit", "view"].includes(value),
  },
  parentCode: Number, // 接收parent_code
});

const emit = defineEmits(["update:modelValue", "done", "open"]);

/** 刷新地区下拉选择数据 */
const reloadRegionSelectData = () => {
  console.log("regionSelectRef", regionSelectRef.value); // 打印regionSelectRef的值
  regionSelectRef.value?.reload?.();
};

defineExpose({ reloadRegionSelectData });

const actionConfigs = {
  add: {
    title: "新增地区",
    button: "新增",
    api: addRegion,
    showFields: [],
    disabledFields: [],
    rules: computed(() => {
      const obj = {
        name: [
          {
            required: true,
            type: "string",
            message: "请输入地区名称",
            trigger: "blur",
          },
        ],
        sort_number: [
          {
            required: true,
            type: "number",
            message: "请输入排序号",
            trigger: "blur",
          },
        ],
      };
      console.log("编辑规则:", obj); // 打印编辑规则，检查是否正确设置了必填项和其他规则
      return obj;
    }),
    beforeOpen: ({ type, formData }) => {
      // 打开前的操作，可以修改表单数据
      formData.parent_code = props.parentCode; // 使用props.organizationId初始化
      console.log("打开前的数据:", formData);
      return { type, formData }; // 必须返回处理后的表单数据
    },
    beforeSubmit: async ({ type, formData }) => {
      // 提交前的操作，可以修改表单数据
      console.log("提交数据:", formData);
      // if (!formData.requiredField) {
      //   return Promise.reject(new Error("缺少必填字段")); // 返回rejected Promise中断流程
      // }
      return { type, formData }; // 必须返回处理后的表单数据
    },
  },
  edit: {
    title: "修改地区",
    button: "修改",
    api: updateRegion, // 补充edit的API
    showFields: [],
    disabledFields: [],
    rules: computed(() => {
      console.log("编辑规则:", form); // 打印编辑规则，检查是否正确设置了必填项和其他规则
      const obj = {
        title: [
          {
            required: true,
            type: "string",
            message: "请输入地区名称",
            trigger: "blur",
          },
        ],
        sort_number: [
          {
            required: true,
            type: "number",
            message: "请输入排序号",
            trigger: "blur",
          },
        ],
      };
      console.log("编辑规则:", obj); // 打印编辑规则，检查是否正确设置了必填项和其他规则
      return obj;
    }),

    beforeOpen: ({ type, formData }) => {
      formData.parent_code =
        props.data.parent_code === 0 ? void 0 : props.data.parent_code; // 确保parent_code的值正确设置
      return { type, formData }; // 必须返回处理后的表单数据
    },
  },
  view: {
    title: "查看地区",
    button: "确定",
    // api: showDictionaryData, // 补充view的API
    showFields: [],
    disabledFields: [],
    rules: {},
  },
};
console.log("parent_code", props.parent_code);

const {
  form,
  resetForm,
  formRef,
  visible,
  loading,
  handleOpen,
  handleSubmit,
  currentRules,
  handleCancel,
} = useFormEdit(props, emit, {
  actionConfigs,
  formFields: {
    parent_code: props.parentCode || undefined, // 使用props.organizationId初始化
    id: void 0,
    name: "",
    sort_number: void 0,
  },
  detailApi: getRegion,
  idField: "id",
});
</script>
